// 封装axios
import axios from "axios";
import store from "@/store";
import { getToken,removeToken } from "./auth";
import { Message } from 'element-ui';
import router from "@/router";

const service = axios.create({
    // baseURL:'http://127.0.0.1:9526/api',
    timeout:50000
})

service.interceptors.request.use(
    config =>{
        if(store.state.user.token){
            config.headers['token'] = getToken();
        }

        return config;
    },

    error =>{
        return Promise.reject(error)
    }
)
service.interceptors.response.use(
    response =>{
        const  res = response.data;
        if (res.code == 403 || res.code == 401 || res.code == 402 ) {
            Message({
                message: res.message || 'Error',
                type: 'error',
                duration: 5 * 1000,
            });
            removeToken();
            router.push('/login/index?redirect='+new Date().getTime());
        }else{
            return res;
        }
    },
    error => {
        console.log('err' + error) // for debug
        Message({
            message: error.message,
            type: 'error',
            duration: 5 * 1000
            })
            return Promise.reject(error)
        }
)

export default service;